package com.example.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.server.bean.Admin;
import com.example.server.util.CurrentAdmin;
import com.example.server.util.RespBean;
import com.example.server.bean.Role;
import com.example.server.config.security.JwtTokenUtil;
import com.example.server.dao.AdminDao;
import com.example.server.dao.RoleDao;
import com.example.server.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 别怿言
 * @since 2023-02-03
 */
@Service
@Transactional
public class AdminServiceImpl extends ServiceImpl<AdminDao, Admin> implements IAdminService {

    @Autowired
    private AdminDao adminDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private BCryptPasswordEncoder encoder;
    @Value("${jwt.tokenhead}")
    private String tokenhead;

    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) {
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)) {
            return RespBean.error("您输入的验证码有误，请重新输入！");
        }
        //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (null == userDetails || !passwordEncoder.matches(password, userDetails.getPassword())) {
            return RespBean.error("用户名或密码错误！");
        }
        if (!userDetails.isEnabled()) {
            return RespBean.error("该账户被禁用！");
        }
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new
                UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("header", tokenhead);
        return RespBean.success("登陆成功", tokenMap);
    }

    @Override
    public Admin getAdminByUserName(String username) {
        return adminDao.selectOne(new QueryWrapper<Admin>().eq("username", username).eq("enabled", true));

    }

    @Override
    public List<Role> getRolesByAdminId(Integer id) {
        return roleDao.getRolesByAdminId(id);
    }

    @Override
    public List<Admin> getAllAdmins(String keyword) {
        return adminDao.getAllAdmins(CurrentAdmin.getCurrentAdmin().getId(), keyword);
    }

    @Override
    public RespBean updateAdminPass(String oldPass, String pass, Integer adminId) {
        Admin admin = adminDao.selectById(adminId);
        if(encoder.matches(oldPass,admin.getPassword())){
            admin.setPassword(encoder.encode(pass));
            if(adminDao.updateById(admin)==1){
                return RespBean.success("更新密码成功！");
            }
        }
        return RespBean.error("更新密码失败！");
    }

    @Override
    public RespBean updateUserface(String url, Integer id, Authentication authentication) {
        Admin admin = adminDao.selectById(id);
        admin.setUserFace(url);
        if(1==adminDao.updateById(admin)){
            Admin principal = (Admin) authentication.getPrincipal();
            principal.setUserFace(url);
            SecurityContextHolder.getContext().setAuthentication(
                    new UsernamePasswordAuthenticationToken(admin,null,authentication.getAuthorities()));
            return RespBean.success("更新成功",url);
        }
        return RespBean.error("更新失败");
    }
}
